from recommendation.recall_layer import RecallLayer
from recommendation.ranking_layer import RankingLayer
from recommendation.diversity_layer import DiversityLayer
import logging
import os

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/recommendation_engine.log'),
        logging.StreamHandler()
    ]
)

class RecommendationEngine:
    def __init__(self):
        # 创建日志目录
        os.makedirs('logs', exist_ok=True)
        
        # 获取日志记录器
        self.logger = logging.getLogger(__name__)
        
        self.recall_layer = RecallLayer()
        self.ranking_layer = RankingLayer()
        self.diversity_layer = DiversityLayer()
    
    def train(self):
        self.logger.info("开始训练推荐系统")
        try:
            self.recall_layer.train_lightfm_model()
            self.logger.info("推荐系统训练完成")
        except Exception as e:
            self.logger.error(f"推荐系统训练失败: {e}")
            raise
    
    def generate_recommendations(self, user_id):
        self.logger.info(f"开始生成用户 {user_id} 的推荐")
        try:
            # 召回层
            candidates = self.recall_layer.recall_candidates(user_id)
            self.logger.info(f"召回层完成，候选商品数量: {len(candidates)}")
            
            # 排序层
            ranked = self.ranking_layer.rank_candidates(candidates, user_id)
            self.logger.info(f"排序层完成，排序后商品数量: {len(ranked)}")
            
            # 多样性控制层
            final_recommendations = self.diversity_layer.apply_diversity(ranked, user_id)
            self.logger.info(f"多样性控制层完成，最终推荐商品数量: {len(final_recommendations)}")
            
            return final_recommendations
        except Exception as e:
            self.logger.error(f"推荐生成失败: {e}")
            return []